package edu.hawaii.examschd;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;

/**
 * Tests the Server class.
 * 
 * @author Jayson Gamiao
 * 
 */
public class TestServer {
  private String address = "localhost";
  private int port = 25109;
  private ServerSocket serverSocket;
  private Socket socket = null;
  private ObjectOutputStream oos;
  private ObjectInputStream ois;
  private boolean continueToRun = true;

  @Test
  /**
   * Test Server class response to a TCP request.
   * @throws Exception
   */
  public void testResponse() throws Exception {
    serverSocket = new ServerSocket(this.port, 5, InetAddress.getByName(this.address));
    new Thread() {
      public void run() {
        try {
          while (continueToRun) {
            Socket socket = serverSocket.accept();

            BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());

            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.flush();
            ObjectInputStream objInputStream = new ObjectInputStream(bis);
          }
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }
    }.start();
  }

  @Test
  /**
   * Initiate a connection to the Server class.
   * @throws Exception
   */
  public void testRequest() throws Exception {
    getSocket();
    oos.writeObject("This is the request from " + Thread.currentThread().getName());
    oos.reset();
    oos.writeObject(Boolean.TRUE);
    oos.flush();
    oos.reset();
  }

  private void getSocket() throws IOException {
    if (socket == null) {
      try {
        socket = new Socket(this.address, this.port);
        BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
        BufferedInputStream in = new BufferedInputStream(socket.getInputStream());

        oos = new ObjectOutputStream(out);
        ois = new ObjectInputStream(in);
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
    else {
      oos.reset();
      oos.writeByte(1);
      oos.flush();
      oos.reset();
      ois.readByte();
    }
  }
}